package com.nsgf.library.ui.monitoring;

import static com.nsgf.library.utils.Utils.generateRandomColor;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.BaseDataBindingAdapter;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.ChartDataBean;
import com.nsgf.library.data.bean.DisplacementBean;
import com.nsgf.library.data.bean.MonitorBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.DialogPickerviewOptionsBinding;
import com.nsgf.library.databinding.FragmentDisplacementVerticalBinding;
import com.nsgf.library.databinding.FragmentGnssVerticalBinding;
import com.nsgf.library.databinding.ItemDialogTestNumBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.ChartListAdapter;
import com.nsgf.library.ui.adapter.SimpleDataBindingPositionAdapter;
import com.nsgf.library.ui.adapter.ViewHolder;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.Kits;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.utils.Utils;
import com.nsgf.library.widget.DisplacementMarkerListView;
import com.nsgf.library.widget.prckerview.OptionsPickerView;
import com.nsgf.library.widget.prckerview.TimePickerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class GNSSVerticalFragment extends BaseFragment {

    public static GNSSVerticalFragment newInstance() {
        GNSSVerticalFragment fragment = new GNSSVerticalFragment();
        return fragment;

    }

    private GNSSVerticalFragmentStates mStates;

    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(GNSSVerticalFragmentStates.class);
        mAccountRequester = getFragmentScopeViewModel(AccountRequester.class);

    }

    private FragmentGnssVerticalBinding mBinding;

    private AccountRequester mAccountRequester;

    protected Typeface tfRegular;


    private ChartListAdapter mAdapterNE;
    private ChartListAdapter mAdapterN;

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        mAdapterNE = new ChartListAdapter(getActivity());
        mAdapterN = new ChartListAdapter(getActivity());


        return new DataBindingConfig(R.layout.fragment_gnss_vertical, BR.vm, mStates)
                .addBindingParam(BR.adapterNE, mAdapterNE)
                .addBindingParam(BR.adapterN, mAdapterN)
                .addBindingParam(BR.click, new ClickProxy());
    }


    DisplacementMarkerListView mv;
    DisplacementMarkerListView mvN;

    private void invalidate() {
        mBinding.chartNE.highlightValue(null);
        mBinding.chartNE.invalidate();
        LineData lineData = new LineData();
        for (int i = 0; i < lineDataSet.size(); i++) {
            if (mStates.chartVerticalDataBean.get().get(i).isChartLineDataSet()) {
                lineData.addDataSet(lineDataSet.get(i));
            }
        }

        if (lineData.getDataSets().isEmpty()) {
            mBinding.chartNE.setData(null);
            mBinding.chartNE.invalidate();
            return;
        }


        mBinding.chartNE.setData(lineData);
        mv.setChartDataBeans(mStates.chartVerticalDataBean.get());
        mBinding.chartNE.setMarker(mv);
        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        mBinding.chartNE.getAxisLeft().setAxisMaximum(max);
        mBinding.chartNE.getAxisLeft().setAxisMinimum(min);
        mBinding.chartNE.invalidate();

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (FragmentGnssVerticalBinding) getBinding();
        tfRegular = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");


        mBinding.chartNE.setNoDataText("暂无相关数据");
        mBinding.chartN.setNoDataText("暂无相关数据");

        mBinding.ivNsgfScale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.llNsgfIndicate.setVisibility(View.GONE);
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mBinding.recyclerViewNE.setLayoutManager(layoutManager);
        mBinding.recyclerViewNE.setItemAnimator(null);
        LinearLayoutManager layoutManagerN = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mBinding.recyclerViewN.setLayoutManager(layoutManagerN);
        mBinding.recyclerViewN.setItemAnimator(null);

        mAccountRequester.getSectionTm(UserInfo.getInstance().getProjectCode(),
                "monitor.obj.1",
                "monitor.type.4");
        mAccountRequester.getMonitorBeanResult().observe(this, responseStatus -> {
            if (responseStatus.getResponseCode() == 200) {

                mStates.monitorVerticalBeanState.set(responseStatus.getData());
                if (savedInstanceState == null) {

                    section = new JsonArray();

                    if (!responseStatus.getData().getSection().isEmpty()) {
                        JsonObject jsonObjectSection = new JsonObject();
                        jsonObjectSection.addProperty("sectionName", responseStatus.getData().getSection().get(0).getSectionName());
                        jsonObjectSection.addProperty("type", responseStatus.getData().getSection().get(0).getType());
                        section.add(jsonObjectSection);
                        mStates.sectionNameVertical.set(responseStatus.getData().getSection().get(0).getPickerViewText());
                    }

                    mStates.startTime.set(responseStatus.getData().getMoMonitorData().getTime());

                    mStates.NEStartTime.set(Kits.Date.getYmd(Kits.Date.timeStrToSecond(responseStatus.getData().getMoMonitorData().getTime())));

                    calendarStarTime.setTimeInMillis(Kits.Date.timeStrToSecond(responseStatus.getData().getMoMonitorData().getTime()));
                    calendarNEStarTime.setTimeInMillis(Kits.Date.timeStrToSecond(responseStatus.getData().getMoMonitorData().getTime()));
                }

                getGNSSDisplacementDist();
                getGNSSProcessLine();

                int orientation = getActivity().getRequestedOrientation();
                Glide.with(getActivity())
                        .load(APIs.BASE_URL_IMG
                                + responseStatus.getData().getFilesSrc())
                        .thumbnail(0.1f)
                        .dontAnimate()
                        .dontTransform()
                        .override(orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ? 800 : 600, orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE ? 600 : 800)
                        .placeholder(R.drawable.__picker_ic_photo_black_48dp)
                        .error(R.drawable.__picker_ic_broken_image_black_48dp)
                        .into(mBinding.ivNsgfScale);

            } else {
                ToastUtils.showLongToast(responseStatus.getMsg());
            }
        });

        mAdapterNE.setOnItemClickListener((viewId, item, position) -> {
            mStates.chartVerticalDataBean.get().get(position).setChartLineDataSet(!item.isChartLineDataSet());
            invalidate();
            mAdapterNE.notifyItemChanged(position);
        });
        mAdapterN.setOnItemClickListener((viewId, item, position) -> {
            mStates.chartVerticalNDataBean.get().get(position).setChartLineDataSet(!item.isChartLineDataSet());
            invalidateNAndE(0, mBinding.chartN, lineDataSetNDirection, mStates.chartVerticalNDataBean.get());
            mAdapterN.notifyItemChanged(position);
        });
    }


    private void invalidateNAndE(int type, LineChart chart, List<LineDataSet> lineDataSet, ArrayList<ChartDataBean> dataBeans) {
        chart.highlightValue(null);
        chart.invalidate();
        LineData lineData = new LineData();
        for (int i = 0; i < lineDataSet.size(); i++) {
            if (dataBeans.get(i).isChartLineDataSet()) {
                lineData.addDataSet(lineDataSet.get(i));
            }
        }

        if (lineData.getDataSets().isEmpty()) {
            chart.setData(null);
            chart.invalidate();
            return;
        }


        chart.setData(lineData);
        mvN.setChartDataBeans(dataBeans);
        chart.setMarker(mvN);
        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        chart.getAxisLeft().setAxisMaximum(max);
        chart.getAxisLeft().setAxisMinimum(min);
        chart.invalidate();

    }

    JsonArray section = new JsonArray();
    JsonObject params = new JsonObject();
    JsonObject paramsNE = new JsonObject();

    List<DisplacementBean> list = new ArrayList<>();

    private void getGNSSDisplacementDist() {
        params.addProperty("monitorCode", mStates.monitorVerticalBeanState.get().getMonitorCode());
        params.addProperty("monitorType", "monitor.obj.4");
        params.add("section", section);
        params.addProperty("startTime", mStates.startTime.get());
        mAccountRequester.getGNSSDisplacementDist(params.toString());
        mAccountRequester.getDisplacementResult().observe(this, listResponseStatus -> {

            if (listResponseStatus.getResponseCode() == 200) {

                mBinding.chartNE.setData(null);
                mBinding.chartNE.invalidate();
                mStates.chartNEDisplacementBean.set((ArrayList<DisplacementBean>) listResponseStatus.getData());
                mStates.chartVerticalDataBean.get().clear();
                if (listResponseStatus.getData().isEmpty()) {
                    mAdapterNE.submitList(new ArrayList<>());
                    return;
                }
                ChartDataBean bean = new ChartDataBean();
                bean.setChartTitles("累计位移量");
                bean.setColor(generateRandomColor(0));
                bean.setChartLineDataSet(true);
                mStates.chartVerticalDataBean.get().add(bean);
                mAdapterNE.submitList(mStates.chartVerticalDataBean.get());
                initLineDataSet(mBinding.chartNE, listResponseStatus.getData());
                setData(mBinding.chartNE, listResponseStatus.getData());

            } else {
                ToastUtils.showShortToast(listResponseStatus.getMsg());
            }

        });
    }

    private void getGNSSProcessLine() {
        paramsNE.addProperty("monitorCode", mStates.monitorVerticalBeanState.get().getMonitorCode());
        paramsNE.addProperty("monitorType", "monitor.type.4");
        paramsNE.add("section", section);
        paramsNE.addProperty("startTime", mStates.NEStartTime.get());
        paramsNE.addProperty("endTime", mStates.NEEndTime.get());
        mAccountRequester.getGNSSProcessLine(paramsNE.toString());
        mAccountRequester.getStringResult().observe(this, new Observer<ResponseStatus<Object>>() {
            @Override
            public void onChanged(ResponseStatus<Object> objectResponseStatus) {


                if (objectResponseStatus.getResponseCode() == 200) {

                    String json = new Gson().toJson(objectResponseStatus.getData());
                    JSONObject jsonObject = null;
                    JSONObject dataList = null;

                    try {
                        jsonObject = new JSONObject(json);
                        points = new JSONArray(jsonObject.get("points").toString());
                        dataList = new JSONObject(jsonObject.get("dataList").toString());
                        times = new JSONArray(jsonObject.get("times").toString());
                        Iterator<String> keys = dataList.keys();

                        int i = 0;
                        mStates.chartVerticalNDataBean.get().clear();
                        list.clear();
                        while (keys.hasNext()) {
                            DisplacementBean displacementBean = new DisplacementBean();
                            String key = keys.next();
                            displacementBean.setTestPoint(key);
                            ChartDataBean bean = new ChartDataBean();
                            bean.setChartTitles(key);
                            bean.setColor(generateRandomColor(i));
                            bean.setChartLineDataSet(true);
                            mStates.chartVerticalNDataBean.get().add(bean);
                            Type listType = new TypeToken<List<DisplacementBean>>() {
                            }.getType();
                            List<DisplacementBean> info = new Gson().fromJson(dataList.get(key).toString(), listType);
                            displacementBean.setBeanList(info);
                            list.add(displacementBean);
                            i++;
                        }

                        //每次载入新数据需情况原有数据 避免出现空指针
                        mBinding.chartN.setData(null);
                        mBinding.chartN.highlightValue(null);
                        mBinding.chartN.invalidate();

                        if (list.isEmpty()) {
                            mAdapterN.submitList(new ArrayList<>());
                            mAdapterN.notifyDataSetChanged();
                            return;
                        }
                        initLineDataSetNAndE(mBinding.chartN);
                        setNAndEData(mBinding.chartN);
                        mAdapterN.submitList(mStates.chartVerticalNDataBean.get());
                        mAdapterN.notifyDataSetChanged();
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    ToastUtils.showShortToast(objectResponseStatus.getMsg());
                }

            }
        });
    }


    public static class GNSSVerticalFragmentStates extends StateHolder {

        public final State<MonitorBean> monitorVerticalBeanState = new State<>(new MonitorBean());//断面 测次 示意图

        public final State<String> sectionNameVertical = new State<>("");

        public final State<String> startTime = new State<>("");
        public final State<String> NEStartTime = new State<>("");
        public final State<String> NEEndTime = new State<>(Kits.Date.getYmd(Calendar.getInstance().getTimeInMillis()));

        public final State<ArrayList<ChartDataBean>> chartVerticalDataBean = new State<>(new ArrayList<>());
        public final State<ArrayList<ChartDataBean>> chartVerticalNDataBean = new State<>(new ArrayList<>());
        public final State<ArrayList<DisplacementBean>> chartVerticalNEDisplacementBean = new State<>(new ArrayList<>());
    }

    private int indexSection = 0;


    private Calendar calendarStarTime = Calendar.getInstance();
    private Calendar calendarNEStarTime = Calendar.getInstance();
    private Calendar calendarNEEndTime = Calendar.getInstance();

    public class ClickProxy {

        /**
         * 来源 8累计垂直位移量分布图 9累计垂直位移量过程线
         * @param type
         */
        public void rotationPreview(int type) {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); // 禁用动画
            if (type == 8) {
                intent.putExtra("title", "累计垂直位移量分布图");
                intent.putExtra("JsonObject", params.toString());
            } else if (type == 9) {
                intent.putExtra("title", "累计垂直位移量过程线");
                intent.putExtra("JsonObject", paramsNE.toString());
            }
            intent.putExtra("type", type)
                    .putExtra("indexSection", indexSection)
                    .putExtra("monitorType", "monitor.type.4")
                    .putExtra("startTime", mStates.startTime.get())
                    .putExtra("NEStartTime", mStates.NEStartTime.get())
                    .putExtra("NEEndTime", mStates.NEEndTime.get())
                    .putExtra("calendarStarTime", calendarStarTime.getTimeInMillis())
                    .putExtra("calendarNEStarTime", calendarNEStarTime.getTimeInMillis())
                    .putExtra("calendarNEEndTime", calendarNEEndTime.getTimeInMillis())
                    .setClass(getActivity(), GNSSLandscapeActivity.class);
            startActivity(intent);
        }

        public void openPreview() {

            mBinding.llNsgfIndicate.setVisibility(View.VISIBLE);
        }

        /**
         * 筛选断面
         */
        public void screenSection() {

            OptionsPickerView<MonitorBean.SectionBean> mOptionsPickerView = new OptionsPickerView.Builder(getActivity(), (options1, options2, options3, v) -> {
                mStates.sectionName.set(mStates.monitorVerticalBeanState.get().getSection().get(options1).getPickerViewText());
                indexSection = options1;
                section = new JsonArray();

                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("sectionName", mStates.monitorVerticalBeanState.get().getSection().get(options1).getSectionName());
                jsonObject.addProperty("type", mStates.monitorVerticalBeanState.get().getSection().get(options1).getType());
                section.add(jsonObject);

                getGNSSDisplacementDist();
                getGNSSProcessLine();
            }).build();
            mOptionsPickerView.setPicker(mStates.monitorVerticalBeanState.get().getSection());
            mOptionsPickerView.setSelectOptions(indexSection);
            mOptionsPickerView.show();
        }


        public void screenTestTime() {

            boolean[] type = new boolean[]{true, true, true, true, false, false};//显示类型 默认全部显示

            Calendar rangDateStart = Calendar.getInstance();
            rangDateStart.set(Calendar.YEAR, rangDateStart.get(Calendar.YEAR) - 10);
            TimePickerView mTimePickerView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mStates.startTime.set(Kits.Date.getYmdh(date.getTime()) + ":00:00");
                    calendarStarTime.setTimeInMillis(date.getTime());
                    getGNSSDisplacementDist();
                }
            }).isCyclic(false)
                    .setRangDate(rangDateStart, Calendar.getInstance())
                    .setType(type)
                    .setTitleText("选择时间")
                    .setDate(calendarStarTime)
                    .build();

            mTimePickerView.show();


        }

        public void screenNEStarTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示
            Calendar rangDateStart = Calendar.getInstance();
            rangDateStart.set(Calendar.YEAR, rangDateStart.get(Calendar.YEAR) - 10);
            TimePickerView mTimePickerView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    calendarNEStarTime.setTimeInMillis(date.getTime());
                    mStates.NEStartTime.set(Kits.Date.getYmd(calendarNEStarTime.getTimeInMillis()));
                    getGNSSProcessLine();
                }
            }).isCyclic(false)
                    .setRangDate(rangDateStart, calendarNEEndTime)
                    .setType(type)
                    .setTitleText("开始时间")
                    .setDate(calendarNEStarTime)
                    .build();

            mTimePickerView.show();


        }

        public void screenNEEndTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mStates.NEEndTime.set(Kits.Date.getYmd(date.getTime()));
                    calendarNEEndTime.setTimeInMillis(date.getTime());
                    getGNSSProcessLine();
                }
            }).isCyclic(false)
                    .setRangDate(calendarNEStarTime, Calendar.getInstance())
                    .setType(type)
                    .setTitleText("结束时间")
                    .setDate(calendarNEEndTime)
                    .build();

            mTimePickerView.show();


        }
    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     */
    private void initLineDataSet(LineChart chart, List<DisplacementBean> list) {

        {   // // Chart Style // //

            // background color
            chart.setBackgroundColor(Color.WHITE);

            //是否展示网格线
            chart.setDrawGridBackground(false);
            //是否显示边界
            chart.setDrawBorders(false);
            // disable description text
            chart.getDescription().setEnabled(false);

            // enable touch gestures
            chart.setTouchEnabled(true);

            // enable scaling and dragging
            chart.setDragEnabled(true);
            chart.setScaleEnabled(true);
            // chart.setScaleXEnabled(true);
            // chart.setScaleYEnabled(true);

            // force pinch zoom along both axis
            chart.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = chart.getXAxis();

            xAxis.setDrawGridLines(false);
            xAxis.setAxisMinimum(0f);
            mBinding.chartNE.moveViewToX(0);
            xAxis.setGranularity(1f);
            // vertical grid lines
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.enableAxisLineDashedLine(10f, 10f, 0f);
            xAxis.setTextColor(getResources().getColor(R.color.color_86909C));
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    if (list.isEmpty() || value < 0)
                        return list.get(0).getTestPoint();
                    if ((int) value >= list.size())
                        return list.get(list.size() - 1).getTestPoint();
                    return list.get((int) value).getTestPoint();
                }
            });
            xAxis.setLabelCount(8, false);
        }

        YAxis yAxis = chart.getAxisLeft();

        // disable dual axis (only use LEFT axis)
        chart.getAxisRight().setEnabled(false);

        yAxis.setTextColor(getResources().getColor(R.color.color_86909C));
        yAxis.setLabelCount(15, false);
        // horizontal grid lines
        yAxis.enableGridDashedLine(10f, 10f, 0f);

        // create marker to display box when values are selected
        if (null != list) {
            mv = new DisplacementMarkerListView(getActivity(), list, mStates.chartVerticalDataBean.get(), 2);
            mv.setChartView(chart);
            chart.setMarker(mv);
            chart.invalidate();
        }
        yAxis.removeAllLimitLines();
        {   // // Create Limit Lines // //
            LimitLine llYAxis = new LimitLine(0, "");
            llYAxis.setLineWidth(0.5f);
//            llYAxis.enableDashedLine(10f, 10f, 0f);
            llYAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
            llYAxis.setLineColor(getResources().getColor(R.color.color_86909C));
            llYAxis.setTypeface(tfRegular);
            // draw limit lines behind data instead of on top
            yAxis.setDrawLimitLinesBehindData(true);

            yAxis.addLimitLine(llYAxis);
        }

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        // draw points over time
        chart.animateX(500);
        chart.animateY(500);

        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();
        //显示位置 左下方
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        // draw legend entries as lines
        l.setForm(Legend.LegendForm.LINE);
        l.setEnabled(false);
        while (!chart.isFullyZoomedOut()) {

            chart.zoomOut();
        }


    }


    List<LineDataSet> lineDataSet = new ArrayList<>();
    List<LineDataSet> lineDataSetNDirection = new ArrayList<>();//N方向累计位移量

    /**
     * 数据加载
     */
    private void setData(LineChart chart, List<DisplacementBean> list) {
        List<Entry> entries = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            Entry entry = new Entry(i, list.get(i).getDisplacement());
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet value = new LineDataSet(entries, "累计位移量");
        value.setColor(mStates.chartVerticalDataBean.get().get(0).getColor());
        value.setCircleColor(mStates.chartVerticalDataBean.get().get(0).getColor());
        value.setLineWidth(1f);
        value.setCircleRadius(1f);
        value.setDrawCircles(false);
        value.setDrawValues(false);
        //设置曲线值的圆点是实心还是空心
        value.setDrawCircleHole(false);
        value.setValueTextSize(10f);
        value.enableDashedHighlightLine(10f, 5f, 0f);
        //设置折线图填充
//        lineDataSet.setDrawFilled(true);
        value.setFormLineWidth(0f);
        value.setFormSize(15.f);
        //设置曲线展示为圆滑曲线（如果不设置则默认折线）
        value.setMode(LineDataSet.Mode.CUBIC_BEZIER);

        value.setFillFormatter(new IFillFormatter() {
            @Override
            public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                return chart.getAxisLeft().getAxisMinimum();
            }
        });
        lineDataSet.clear();
        lineDataSet.add(value);
        LineData lineData = new LineData(lineDataSet.get(0));
        chart.setData(lineData);

        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        chart.getAxisLeft().setAxisMaximum(max);
        chart.getAxisLeft().setAxisMinimum(min);

    }


    JSONArray points = null;
    JSONArray times = null;

    private void setNAndEData(LineChart chart) {
        lineDataSetNDirection.clear();
        LineData lineData = new LineData();
        for (int j = 0; j < list.size(); j++) {

            List<Entry> entries = new ArrayList<>();
            for (int i = 0; i < list.get(j).getBeanList().size(); i++) {
                Entry entry = new Entry(i, list.get(j).getBeanList().get(i).getDisplacement());
                entries.add(entry);
            }
            // 每一个LineDataSet代表一条线
            LineDataSet value = new LineDataSet(entries, list.get(j).getTestPoint());

            value.setColor(mStates.chartVerticalNDataBean.get().get(j).getColor());
            value.setCircleColor(mStates.chartVerticalNDataBean.get().get(j).getColor());
            value.setLineWidth(1f);
            value.setCircleRadius(1f);
            value.setDrawCircles(false);
            value.setDrawValues(false);
            //设置曲线值的圆点是实心还是空心
            value.setDrawCircleHole(false);
            value.setValueTextSize(10f);
            value.enableDashedHighlightLine(10f, 5f, 0f);
            //设置折线图填充
//        lineDataSet.setDrawFilled(true);
            value.setFormLineWidth(0f);
            value.setFormSize(15.f);
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            value.setMode(LineDataSet.Mode.CUBIC_BEZIER);

            value.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return chart.getAxisLeft().getAxisMinimum();
                }
            });
            lineDataSetNDirection.add(value);
            lineData.addDataSet(value);
        }
        chart.setData(lineData);

        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        chart.getAxisLeft().setAxisMaximum(max);
        chart.getAxisLeft().setAxisMinimum(min);

    }


    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     */
    private void initLineDataSetNAndE(LineChart chart) {

        {   // // Chart Style // //

            // background color
            chart.setBackgroundColor(Color.WHITE);

            //是否展示网格线
            chart.setDrawGridBackground(false);
            //是否显示边界
            chart.setDrawBorders(false);
            // disable description text
            chart.getDescription().setEnabled(false);

            // enable touch gestures
            chart.setTouchEnabled(true);

            // enable scaling and dragging
            chart.setDragEnabled(true);
            chart.setScaleEnabled(true);
            // chart.setScaleXEnabled(true);
            // chart.setScaleYEnabled(true);

            // force pinch zoom along both axis
            chart.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = chart.getXAxis();

            xAxis.setDrawGridLines(false);
            xAxis.setAxisMinimum(-1f);
            xAxis.setAxisMaximum(times.length());
            mBinding.chartNE.moveViewToX(0);
            xAxis.setGranularity(1f);
            // vertical grid lines
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.enableAxisLineDashedLine(10f, 10f, 0f);
            xAxis.setTextColor(getResources().getColor(R.color.color_86909C));
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    try {
                        if ((int) value < 0)
                            return "";
                        if ((int) value >= times.length())
                            return "";
                        return Utils.formatTimeMD(times.get((int) value).toString());
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            xAxis.setLabelRotationAngle(-30f);
            xAxis.setLabelCount(8, false);
        }

        YAxis yAxis = chart.getAxisLeft();

        // disable dual axis (only use LEFT axis)
        chart.getAxisRight().setEnabled(false);

        yAxis.setTextColor(getResources().getColor(R.color.color_86909C));
        yAxis.setLabelCount(15, false);
        // horizontal grid lines
        yAxis.enableGridDashedLine(10f, 10f, 0f);

        // create marker to display box when values are selected
        if (null != list) {
            mvN = new DisplacementMarkerListView(getActivity(), list, mStates.chartVerticalNDataBean.get(), true, 2);
            mvN.setChartView(chart);
            chart.setMarker(mvN);
            chart.invalidate();
        }

        yAxis.removeAllLimitLines();
        {   // // Create Limit Lines // //
            LimitLine llYAxis = new LimitLine(0, "");
            llYAxis.setLineWidth(0.5f);
//            llYAxis.enableDashedLine(10f, 10f, 0f);
            llYAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
            llYAxis.setLineColor(getResources().getColor(R.color.color_86909C));
            llYAxis.setTypeface(tfRegular);
            // draw limit lines behind data instead of on top
            yAxis.setDrawLimitLinesBehindData(true);

            yAxis.addLimitLine(llYAxis);
        }

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        // draw points over time
        chart.animateX(500);
        chart.animateY(500);

        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();
        //显示位置 左下方
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        // draw legend entries as lines
        l.setForm(Legend.LegendForm.LINE);
        l.setEnabled(false);
        while (!chart.isFullyZoomedOut()) {

            chart.zoomOut();
        }


    }
}
